import { AppServiceUtility } from "src/projects/app/appService";
import { edit_props_info, beforeUpload } from "src/projects/app/util-tool";
import { addon, Permission } from "pao-aop";
import { reactControl, ReactViewControl, ReactViewState, ReactView } from "pao-aop-client";
import { MainContent } from "src/business/components/style-components/main-content";
import { isPermission } from "src/projects/app/permission";
import React from "react";
import FormCreator, { InputType } from "src/business/components/buss-components/form-creator";
import { GetFieldDecoratorOptions } from "antd/lib/form/Form";
// import { ROUTE_PATH } from "src/projects/router";
import { request } from "src/business/util_tool";
import { Select, Card, Row, Button, message, Steps, Result } from 'antd';
let { Option } = Select;
import moment from 'moment';
import { remote } from "src/projects/remote";
import TextArea from "antd/lib/input/TextArea";
import { ActivityInfo } from "./activityInfo";
import { checkPhone, checkMin1, checkMin0 } from './validate';
const { Step } = Steps;
/**
 * 状态：活动新增页面
 */
export interface ChangeActivityPublishViewState extends ReactViewState {
    /** 服务商列表 */
    provider_list?: [];
    /** 活动类型列表 */
    activity_type_list?: [];
    /** 活动室 */
    activity_room_list?: [];
    // 审批内容
    sp_msg?: string;
    // 是否发送
    is_send?: boolean;
    // 发布步骤
    activity_step: any;
    // 申请步骤
    step?: number;
    // 状态
    status?: string;
    // 活动内容
    activity_info?: any;
    // 参数code
    paramCode?: any;
    // 参数key
    paramKey?: any;
    // 带参
    select_type?: any;
    endOpen?: any;
    begin_date?: any;
    end_date?: any;
}

/**
 * 组件：活动新增页面视图
 */
export class ChangeActivityPublishView extends ReactView<ChangeActivityPublishViewControl, ChangeActivityPublishViewState> {
    constructor(props: ChangeActivityPublishViewControl) {
        super(props);
        this.state = {
            provider_list: [],
            activity_type_list: [],
            activity_room_list: [],
            sp_msg: '',
            is_send: false,
            endOpen: false,
            begin_date: false,
            end_date: false,
            step: -2,
            status: '',
            activity_info: [],
            activity_step: [{
                'step_name': '发布',
            }, {
                'step_name': '审核',
            }, {
                'step_name': '完成',
            }],
            paramCode: this.props.match!.params.code,
            paramKey: this.props.match!.params.key,
            select_type: this.props.select_param && this.props.select_param['type'] ? this.props.select_param['type'] : '',
        };
    }
    componentDidMount() {
        const { paramKey, select_type } = this.state;
        let param: any = { id: paramKey };
        if (select_type) {
            if (select_type === 'view') {
                param['all'] = 'sh';
            } else if (select_type === 'change') {
                param['all'] = 'all';
            }
        }
        if (paramKey) {
            request(this, AppServiceUtility.activity_service.get_activity_list!(param, 1, 1))
                .then((datas: any) => {
                    let step_no = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['step_no']) ? datas.result[0]['new_field'][0]['step_no'] : ((datas.result && datas.result[0] && datas.result[0]['step_no']) ? datas.result[0]['step_no'] : -1);
                    let status = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['status']) ? datas.result[0]['new_field'][0]['status'] : ((datas.result && datas.result[0] && datas.result[0]['status']) ? datas.result[0]['status'] : '未知');
                    let activity_info = (datas.result && datas.result[0]) ? datas.result[0] : [];
                    this.setState({
                        step: step_no,
                        status,
                        activity_info,
                    });
                });
        } else {
            this.setState({
                step: 0,
                status: '待审批',
            });
        }
        request(this, AppServiceUtility.person_org_manage_service.get_organization_list!({}))
            .then((datas: any) => {
                this.setState({
                    provider_list: datas.result,
                });
            });
        request(this, AppServiceUtility.activity_service.get_activity_type_list!({}))
            .then((datas: any) => {
                this.setState({
                    activity_type_list: datas.result,
                });
            });
        // 获取活动室
        request(this, AppServiceUtility.activity_service.get_activity_room_list!({}, 1, 99)!)
            .then((datas: any) => {
                this.setState({
                    activity_room_list: datas.result,
                });
            });
    }
    getDataValue(value: string) {
        // 此时的value为moment可以直接进行装换
        value = moment(value).format('YYYY-MM-DD HH:mm:ss'); // 转换 
    }
    setRejectReason(e: any) {
        this.setState({
            sp_msg: e.target.value,
        });
    }
    setParam(step_no: number, status: string, sp_status: string, notcie: string) {
        let { sp_msg, activity_info } = this.state;
        if (sp_status === '不通过' && sp_msg === '') {
            message.error('不通过请填写原因');
            return;
        }
        let param: any = {
            // 审批标识
            'is_sp': 1,
            // 审批状态
            'sp_status': sp_status,
            // 主数据状态
            'status': status,
            // 审批信息
            'sp_msg': sp_msg,
            // 步骤
            'step_no': step_no,
            // 主键ID
            'id': activity_info['id'],
        };
        this.changeStatus(param, notcie);
    }
    reChange() {
        let activity_step = this.state.activity_step;
        activity_step[0]['step_name'] = '重新编辑';
        this.setState({
            step: 1,
            select_type: 'change',
            status: '重新编辑',
            activity_step,
        });
    }
    changeStatus(value: any, notice: string) {
        const is_send = this.state.is_send;
        const that = this;
        notice = notice || '操作成功！';
        // 正在发送请求
        if (is_send === true) {
            message.error('请勿操作过快！');
            return;
        }
        this.setState(
            {
                is_send: true,
            },
            () => {
                request(that, AppServiceUtility.activity_service.update_activity!(value))
                    .then((data: any) => {
                        if (data === 'Success') {
                            // that.setState({
                            //     is_send: false,
                            // });
                            message.success(notice, 3, () => history.back());
                        } else {
                            message.error(data);
                        }
                    }).catch((error: Error) => {
                        message.error(error.message);
                    });
            }
        );
        return;
    }
    changeOrganization(e: any) {
        // 获取活动室
        request(this, AppServiceUtility.activity_service.get_activity_room_list!({ organization_id: e }, 1, 99)!)
            .then((datas: any) => {
                this.setState({
                    activity_room_list: datas.result,
                });
            });
    }
    handleStartOpenChange = (open: any) => {
        if (!open) {
            this.setState({ endOpen: true });
        }
    }
    handleEndOpenChange = (open: any) => {
        this.setState({ endOpen: open });
    }
    onBeginChange(value: any) {
        this.setState({
            'begin_date': value,
        });
    }
    onEndChange(value: any) {
        this.setState({
            'end_date': value,
        });
    }
    disabledEndDate(endValue: any) {
        const { begin_date } = this.state;
        if (!endValue || !begin_date) {
            return false;
        }
        return endValue.valueOf() <= begin_date.valueOf();
    }
    returnPublishForm() {
        const activity_room_list: JSX.Element[] = this.state.activity_room_list!.map((item, idx) => <Option key={item['id']}>{item['activity_room_name']}</Option>);
        const activity_type_list: JSX.Element[] = this.state.activity_type_list!.map((item, idx) => <Option key={item['id']}>{item['name']}</Option>);
        let provider = this.state.provider_list;
        let provider_list: any[] = [];
        provider!.map((item, idx) => {
            provider_list.push(<Option key={item['id']}>{item['name']}</Option>);
        });
        const paramKey = this.state.paramKey;
        let edit_props = {
            form_items_props: [{
                title: "活动发布信息",
                need_card: true,
                input_props: [
                    {
                        type: InputType.antd_input,
                        label: "活动名称",
                        decorator_id: "activity_name",
                        field_decorator_option: {
                            rules: [{ required: true, message: "请输入活动名称" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入活动名称",
                            autocomplete: 'off',
                        }
                    }, {
                        type: InputType.select,
                        label: "活动类型",
                        decorator_id: "activity_type_id",
                        field_decorator_option: {
                            rules: [{ required: true, message: "请选择活动类型" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请选择活动类型",
                            childrens: activity_type_list,
                            autocomplete: 'off',
                        }
                    }, {
                        type: InputType.upload,
                        label: "活动图片",
                        decorator_id: "photo",
                        field_decorator_option: {
                            // rules: [{ required: true, message: "请输入活动图片" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            action: remote.upload_url,
                            beforeUpload: beforeUpload
                        }
                    }, {
                        type: InputType.select,
                        label: "商家",
                        decorator_id: "organization_id",
                        field_decorator_option: {
                            rules: [{ required: true, message: "请选择商家" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请选择商家",
                            childrens: provider_list,
                            autocomplete: 'off',
                            onChange: (e: any) => this.changeOrganization(e),
                        }
                    }, {
                        type: InputType.antd_input,
                        label: "最大参与人数",
                        decorator_id: "max_quantity",
                        field_decorator_option: {
                            rules: [{
                                required: true,
                                validator: (_: any, value: any, cb: any) => checkMin1(_, value, cb, '最大参与人数')
                            }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入最大参与人数",
                            autocomplete: 'off',
                        }
                    },
                    // {
                    //     type: InputType.rangePicker,
                    //     label: "活动时间",
                    //     decorator_id: "range_date",
                    //     field_decorator_option: {
                    //         rules: [{ required: true, message: "请选择活动时间" }],
                    //     } as GetFieldDecoratorOptions,
                    //     option: {
                    //         placeholder: ['请选择开始时间', '请选择结束时间'],
                    //         format: "YYYY-MM-DD HH:mm:ss",
                    //         showTime: true,
                    //         autocomplete: 'off',
                    //     }
                    // },
                    {
                        type: InputType.date,
                        label: "活动开始时间",
                        decorator_id: "begin_date",
                        field_decorator_option: {
                            rules: [{ required: true, message: "请输入活动开始时间" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入活动开始时间",
                            format: "YYYY-MM-DD HH:mm:ss",
                            showTime: true,
                            autocomplete: 'off',
                            onChange: (e: any) => this.onBeginChange(e),
                            onOpenChange: (e: any) => this.handleStartOpenChange(e),
                        }
                    }, {
                        type: InputType.date,
                        label: "活动结束时间",
                        decorator_id: "end_date",
                        field_decorator_option: {
                            rules: [{ required: true, message: "请输入活动结束时间" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入活动结束时间",
                            format: "YYYY-MM-DD HH:mm:ss",
                            onOk: this.getDataValue,
                            showTime: true,
                            autocomplete: 'off',
                            open: this.state.endOpen,
                            onChange: (e: any) => this.onEndChange(e),
                            onOpenChange: (e: any) => this.handleEndOpenChange(e),
                            disabledDate: (e: any) => this.disabledEndDate(e)
                        }
                    }, {
                        type: InputType.antd_input,
                        label: "活动地点",
                        decorator_id: "address",
                        field_decorator_option: {
                            rules: [{ required: true, message: "请输入活动地点" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入活动地点",
                            autocomplete: 'off',
                        }
                    }, {
                        type: InputType.select,
                        label: "活动场室",
                        decorator_id: "activity_room_id",
                        field_decorator_option: {
                            rules: [{
                                message: "请选择活动场室"
                            }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: activity_room_list.length === 0 ? "当前无可选活动室" : "请选择活动场室",
                            childrens: activity_room_list,
                            autocomplete: 'off',
                            disabled: activity_room_list.length === 0 ? true : false
                        }
                    }, {
                        type: InputType.antd_input,
                        label: "联系人",
                        decorator_id: "contacts",
                        field_decorator_option: {
                            rules: [{ required: true, message: "请输入联系人" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入联系人",
                            autocomplete: 'off',
                        }
                    }, {
                        type: InputType.antd_input,
                        label: "联系人电话",
                        decorator_id: "phone",
                        field_decorator_option: {
                            rules: [{
                                required: true,
                                validator: (_: any, value: any, cb: any) => checkPhone(_, value, cb, '联系人电话')
                            }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入联系人电话",
                            autocomplete: 'off',
                        }
                    }, {
                        type: InputType.antd_input,
                        label: "活动金额",
                        decorator_id: "amount",
                        field_decorator_option: {
                            rules: [{
                                required: true,
                                validator: (_: any, value: any, cb: any) => checkMin0(_, value, cb, '活动金额')
                            }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入活动金额",
                            autocomplete: 'off',
                        }
                    }, {
                        type: InputType.nt_rich_text,
                        label: "活动介绍",
                        decorator_id: "introduce",
                        field_decorator_option: {
                            // rules: [{ required: true, message: "请输入活动介绍" }],
                        } as GetFieldDecoratorOptions,
                        option: {
                            placeholder: "请输入活动介绍",
                            autocomplete: 'off',
                        }
                    },
                ]
            }],
            other_btn_propps: [{
                text: "返回",
                cb: () => {
                    // this.props.history!.push(ROUTE_PATH.activityManage);
                    history.back();
                }
            }],
            submit_btn_propps: {
                text: "发布",
            },
            service_option: {
                service_object: AppServiceUtility.activity_service,
                operation_option: {
                    query: {
                        func_name: "get_activity_list_all",
                        arguments: [{ id: paramKey, all: 'all' }, 1, 1]
                    },
                    save: {
                        func_name: "update_activity"
                    }
                },
            },
            succ_func: () => {
                // this.props.history!.push(ROUTE_PATH.activityManage); 
                history.back();
            },
            id: paramKey,
        };
        let edit_props_list = Object.assign(edit_props, edit_props_info);
        return (
            <FormCreator {...edit_props_list} />
        );
    }
    returnInfoSH() {
        let { paramCode, activity_info } = this.state;
        return (
            <Card>
                <ActivityInfo activity_info={activity_info} />
                {paramCode ? null : <Row>
                    <br />
                    <Row>不通过请填写原因</Row>
                    <br />
                    <TextArea rows={4} onChange={(e) => { this.setRejectReason(e); }} />
                    <Row type="flex" justify="center" className="ctrl-btns">
                        <Button onClick={() => this.setParam(1, '不通过', '不通过', '')}>不通过</Button>
                        <Button type="primary" onClick={() => this.setParam(2, '通过', '通过', '')}>审批通过</Button>
                        <Button onClick={() => history.back()}>返回</Button>
                    </Row>
                </Row>}
            </Card>
        );
    }
    render() {
        const redeirect = isPermission(this.props.permission!);
        if (redeirect) {
            return redeirect;
        }
        let { step, status, activity_info, activity_step, select_type } = this.state;
        let stepStatus: any = {};
        if (status === '不通过') {
            stepStatus.status = 'error';
        }
        // 判断是否编辑状态，步骤为1并且是编辑标识状态
        const isEditable = step === 1 && select_type === 'change';
        // step为-1代表完成了，取数组长度
        step = isEditable ? 0 : (step === -1 ? activity_step.length - 1 : step);
        return (
            <MainContent>
                <Steps current={step} {...stepStatus} style={{ background: "white", padding: "25px" }}>
                    {activity_step.map((item: any, index: number) => {
                        return (
                            <Step key={index} title={item.step_name} />
                        );
                    })}
                </Steps>
                {(() => {
                    if (status === '不通过') {
                        return (
                            <Card>
                                <Result
                                    status="error"
                                    title="审批不通过"
                                    subTitle={'不通过原因：' + (activity_info['sp_msg'] || '暂无')}
                                />
                                <ActivityInfo activity_info={activity_info} />
                                <Row type="flex" justify="center" className="ctrl-btns">
                                    <Button onClick={() => history.back()}>返回</Button>
                                </Row>
                            </Card>
                        );
                    } else if (status === '通过') {
                        return (
                            <Card>
                                <Result
                                    status="success"
                                    title="完成"
                                    subTitle={`审核通过！`}
                                />
                                <ActivityInfo activity_info={activity_info} />
                                <Row type="flex" justify="center" className="ctrl-btns">
                                    <Button onClick={() => history.back()}>返回</Button>
                                    <Button onClick={() => this.reChange()}>重新编辑</Button>
                                </Row>
                            </Card>
                        );
                    } else {
                        if (isEditable || step === 0) {
                            // 申请表
                            return this.returnPublishForm();
                        } else if (step === 1) {
                            // 资料审批
                            return this.returnInfoSH();
                        }
                    }
                    return null;
                })()}
            </MainContent>
        );
    }
}

/**
 * 控件：活动新增页面控件
 * @description 活动新增页面控件
 * @author
 */
@addon('ChangeActivityPublishViewControl', '活动新增页面控件', '活动新增页面控件')
@reactControl(ChangeActivityPublishView, true)
export class ChangeActivityPublishViewControl extends ReactViewControl {
    /** 视图权限 */
    public permission?: Permission;
    /** 带参 */
    public select_param?: any;
}